package cn.hunqing.web.controller;

import java.util.List;

import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import cn.hunqing.web.dto.InvitationForm;
import cn.hunqing.web.dto.MyCardSimpleDto;
import cn.hunqing.web.dto.TemplateSimpleDto;
import cn.hunqing.web.msg.MakeInvitationMsgs;
import cn.hunqing.web.param.MakeInvitationParameters;
import cn.hunqing.web.param.MyCardParameters;
import cn.hunqing.web.service.TemplateService;
import cn.hunqing.web.service.WeddingInvitationService;
import cn.hunqing.web.util.PathConstants;
import cn.hunqing.web.util.SessionUtils;
import cn.hunqing.web.util.ViewConstants;

@Controller
public class MakeInvitationController {
	private static Logger logger = LoggerFactory.getLogger(MakeInvitationController.class);

	@Autowired
	private TemplateService templateService;
	
	@Autowired
	private WeddingInvitationService weddingInvitationService;
	
	@RequestMapping(PathConstants.PATH_MAKE_CARD+"/{templateId}/{version}")
    public String doMakeGet(final ModelMap modelMap, @PathVariable String templateId, @PathVariable String version,HttpSession httpSession) {
		logger.info("Make the invitation by the template:{}",templateId);
		if(StringUtils.isEmpty(templateId)){
			modelMap.put(MakeInvitationParameters.RESPONSE_ERROR_MSG, MakeInvitationMsgs.EMPTY_TEMPLATE_ID);
			return ViewConstants.VIEW_ERROR;
		}
		TemplateSimpleDto templateSimpleDto  =templateService.getTemplate(templateId);
		if(templateSimpleDto == null){
			modelMap.put(MakeInvitationParameters.RESPONSE_ERROR_MSG, MakeInvitationMsgs.NOT_FOUND_TEMPLATE);
			return ViewConstants.VIEW_ERROR;
		}
		InvitationForm invitationForm = null;
		Object invitationFormObj = httpSession.getAttribute(MakeInvitationParameters.SESSION_FORM_INVITATION);
		if(invitationFormObj == null || !(invitationFormObj instanceof InvitationForm)){
			invitationForm = new InvitationForm();
			invitationForm.setLoveStoryPictureSelected(true);
			invitationForm.setLoveStoryVideoSelected(true);
		}else{
			httpSession.removeAttribute(MakeInvitationParameters.SESSION_FORM_INVITATION);
			invitationForm = (InvitationForm)invitationFormObj;
		}
		invitationForm.setAction(InvitationForm.ACTION_MAKE);
		invitationForm.setTemplateId(templateSimpleDto.getTemplateId());
        modelMap.addAttribute(MakeInvitationParameters.SESSION_FORM_INVITATION, invitationForm);
        return ViewConstants.VIEW_MAKE_CARD;
    }

    /**
     * The successful finish step ('_finish' request param must be present)
     */
    @RequestMapping(value = PathConstants.PATH_MAKE_CARD,method = RequestMethod.POST)
    public String doPost(final @ModelAttribute(MakeInvitationParameters.SESSION_FORM_INVITATION) InvitationForm invitationForm,
                                final Errors errors,
                                final ModelMap modelMap,HttpSession httpSession) {
    	int weddingInvitationId;
		try {
			weddingInvitationId = processInvitationForm(modelMap, httpSession, invitationForm);
	    	logger.info("Create or update wedding invitation id:{}",weddingInvitationId);
	    	if(StringUtils.equals(InvitationForm.SUBMIT_PREVIEW, invitationForm.getSubmit())){
	    		logger.info("Get the preview request");
	    		return "redirect:"+PathConstants.PATH_MY_CARD+"/"+weddingInvitationId+"/preview/v2";
	    	}else if(StringUtils.equals(InvitationForm.SUBMIT_SAVE, invitationForm.getSubmit())){
	    		logger.info("Get the save request");
	    		return "redirect:"+PathConstants.PATH_MY_CARD+"/v2";
	    	}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	modelMap.put(MakeInvitationParameters.RESPONSE_ERROR_MSG, MakeInvitationMsgs.WRONG_ACTION);
		return ViewConstants.VIEW_ERROR;
       
    }

	@RequestMapping(PathConstants.PATH_EDIT_CARD+"/{weddingInvitationId}/{version}")
    public String doEditGet(final ModelMap modelMap, @PathVariable String weddingInvitationId,@PathVariable String version,HttpSession httpSession) {
		logger.info("Edit the invitation by the cardId:{}",weddingInvitationId);
        // put your initial command

		if(StringUtils.isEmpty(weddingInvitationId)){
			modelMap.put(MakeInvitationParameters.RESPONSE_ERROR_MSG, MakeInvitationMsgs.EMPTY_CARD_ID);
			return ViewConstants.VIEW_ERROR;
		}
		if(!StringUtils.isNumeric(weddingInvitationId)){
			modelMap.put(MakeInvitationParameters.RESPONSE_ERROR_MSG, MakeInvitationMsgs.WRONG_CARD_ID);
			return ViewConstants.VIEW_ERROR;
		}

		int weddingInvitationIdInt = Integer.parseInt(weddingInvitationId);
		
		int userId = SessionUtils.getUserId(httpSession);
		InvitationForm invitationForm  = null;
		try{
			invitationForm  = weddingInvitationService.getInvitationFormData(weddingInvitationIdInt, userId);
		}catch(Throwable e){
			logger.error("Exception:", e);
			modelMap.put(MakeInvitationParameters.RESPONSE_ERROR_MSG, e.getMessage());
			return ViewConstants.VIEW_ERROR;
		}
		
		if(invitationForm == null){
			modelMap.put(MakeInvitationParameters.RESPONSE_ERROR_MSG, MakeInvitationMsgs.NOT_FOUND_CARD);
			return ViewConstants.VIEW_ERROR;
		}
		invitationForm.setAction(InvitationForm.ACTION_EDIT);
        modelMap.addAttribute(MakeInvitationParameters.SESSION_FORM_INVITATION, invitationForm);
        return ViewConstants.VIEW_MAKE_CARD;
    }
	
	@RequestMapping(PathConstants.PATH_DELETE_CARD+"/{weddingInvitationId}/{version}")
	public String doDeleteGet(final ModelMap modelMap,@PathVariable String weddingInvitationId, HttpSession httpSession){
		if(StringUtils.isEmpty(weddingInvitationId)){
			modelMap.put(MakeInvitationParameters.RESPONSE_ERROR_MSG, MakeInvitationMsgs.EMPTY_CARD_ID);
			return ViewConstants.VIEW_ERROR;
		}
		if(!StringUtils.isNumeric(weddingInvitationId)){
			modelMap.put(MakeInvitationParameters.RESPONSE_ERROR_MSG, MakeInvitationMsgs.WRONG_CARD_ID);
			return ViewConstants.VIEW_ERROR;
		}
		int weddingInvitationIdInt = Integer.parseInt(weddingInvitationId);
		Integer userId = SessionUtils.getUserId(httpSession);
		if(userId == null){
			return ViewConstants.VIEW_LOGIN;
		}
		try {
			weddingInvitationService.deleteMyCardById(weddingInvitationIdInt);
		} catch (Exception e) {
			modelMap.put(MakeInvitationParameters.RESPONSE_ERROR_MSG, "删除喜帖出错");
			return ViewConstants.VIEW_ERROR;
		}
		List<MyCardSimpleDto> result = weddingInvitationService.getMyCards(userId);
		modelMap.put(MyCardParameters.RESPONSE_CARDS, result);
		return ViewConstants.VIEW_MY_CARD;
	}

	private int processInvitationForm(final ModelMap modelMap, HttpSession httpSession,
			InvitationForm invitationForm) throws Exception{
		// some stuff
		if(StringUtils.equals(InvitationForm.ACTION_MAKE, invitationForm.getAction())){
			int userId = SessionUtils.getUserId(httpSession);
			return weddingInvitationService.create(invitationForm,userId,userId);
			
		}else if(StringUtils.equals(InvitationForm.ACTION_EDIT, invitationForm.getAction())){
			logger.info("To edit new wedding invitation");
			int userId = SessionUtils.getUserId(httpSession);
			return weddingInvitationService.update(invitationForm,userId);
		}else{
			throw new Exception("Unsupport operation");
		}
	}

}
